<template>
    <div>
        <el-dialog :title="state.dialog.title" v-model="state.dialog.visible" width="1500px" append-to-body>
            <el-form ref="projectFormRef" :model="form" :rules="rules" label-width="120px">
<!--              <el-row style="width: 100%;border: 1px solid red;display: flex;justify-content:space-between;">-->
                <el-descriptions :column="3" border>
                  <el-descriptions-item label="项目名称" prop="name">
                    <el-input v-model="form.name"  class="mt10" placeholder="请输入项目名称" />
                  </el-descriptions-item>
                  <el-descriptions-item label="项目周期" prop="projectDate">
                    <el-date-picker v-model="form.projectDate"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                                    style="max-width: 280px" />
                  </el-descriptions-item>

                  <el-descriptions-item label="关联项目" prop="productId">
                    <el-select v-model="form.productId" @change="handelProduct()" style="width: 250px">
                      <el-option v-for="dict in state.productList"
                                 :key="dict.id"
                                 :label="dict.name"
                                 :value="dict.id" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="负责人" prop="directorUid">
                    <el-select v-model="form.directorUid" >
                      <el-option v-for="dict in state.userList"
                                 :key="dict.userId"
                                 :label="dict.nickName"
                                 :value="dict.userId" />
                    </el-select>
                  </el-descriptions-item>
                  <el-descriptions-item label="成员" prop="checkAdminIds" :span="2">
                    <el-select v-model="form.checkAdminIds" :multiple-limit="10" multiple>
                      <el-option v-for="dict in state.userList"
                                 :key="dict.userId"
                                 :label="dict.nickName"
                                 :value="dict.userId" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="项目描述" :span="3">
                    <el-input type="textarea" v-model="form.content" rows="3" maxlength="200"/>
                  </el-descriptions-item>
                  <el-descriptions-item label="markdown项目描述" :span="3">
                    <mdEdit ref="editor" v-model="form.mdContent" mode="edit" />
                  </el-descriptions-item>
                  <el-descriptions-item label="项目阶段" :span="3">
                    <el-row v-for="(item,index) in form.manageStepList" :key="item" style="width: 100%;display: flex;justify-content: space-between;margin: 5px 0;padding: 0 5px">
                      <el-col :span="23">
                        <el-row>
                          <el-col :span="6" style="padding: 0 3px">
                            <el-select v-model="item.flowName" filterable placeholder="请选择/输入公司名称">
                              <el-option v-for="dict in state.stepList" :key="dict.id" :label="dict.title" :value="dict.id" />
                              <template #prefix>
                                第{{index+1}}阶段
                              </template>
                            </el-select>
                          </el-col>
                          <el-col :span="6" style="padding: 0 3px">
                            <el-select v-model="item.flowUid" >
                              <el-option v-for="dict in state.userList"
                                         :key="dict.userId"
                                         :label="dict.nickName"
                                         :value="dict.userId" />
                              <template #prefix>
                                负责人
                              </template>
                            </el-select>
                          </el-col>
                          <el-col :span="6" style="padding: 0 3px">
                            <el-select v-model="item.checkAdminIds" :multiple-limit="10" multiple>
                              <el-option v-for="dict in state.userList"
                                         :key="dict.userId"
                                         :label="dict.nickName"
                                         :value="dict.userId" />
                              <template #prefix>
                                成员
                              </template>
                            </el-select>
                          </el-col>
                          <el-col :span="6" style="padding: 0 3px">
                            <el-date-picker v-model="item.projectDate"
                                            type="daterange"
                                            range-separator="至"
                                            start-placeholder="开始时间"
                                            end-placeholder="结束时间"
                                            value-format="YYYY-MM-DD HH:mm:ss"
                                            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                                            style="max-width: 250px;" >
                              <template #prefix>
                                周期
                              </template>
                            </el-date-picker>
                          </el-col>
                        </el-row>
                      </el-col>
                      <el-col :span="1">
                        <el-button :disabled="!index>0" type="danger" @click="handelDell(index)" style="margin-left: -20px">删除</el-button>
                      </el-col>
                    </el-row>
                  </el-descriptions-item>
                </el-descriptions>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="state.buttonLoading" :disabled ="state.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup name="ProjectAdd" lang="ts">
    import {nextTick, reactive, ref, toRefs} from "vue";
    import { ElForm, ElMessage} from "element-plus";
    import { getProject, addProject, updateProject } from '@/leadmall/api/project';
    import { ProjectVO, ProjectForm } from '@/leadmall/api/project/types';
    import mdEdit from "@/components/mdEedit/index.vue";
    import { useUser } from "@/api/system/user";
    import {getProductlist} from "@/leadmall/api/product";
    import {getWorkList} from "@/leadmall/api/workCate";

    const projectFormRef = ref(ElForm as any);
    const state = reactive({
        form: {} as any,
        rules:{},
        buttonLoading:false,
        dialog:{
            visible: false,
            title: ''
        },
      userList:[],
      productList:[],
      stepList:[],
    });
    const {form ,rules} = toRefs(state);
    const emit = defineEmits(["refresh"]);
    /** 表单重置 */
    const reset = () => {
        form.value = Object.assign({},initFormData);
            projectFormRef.value = {};
    }

    const handelProduct=()=>{
      let workType = state.productList.forEach((item : any) => {
        if(form.value.productId == item.id){
          return item.workType;
        }
      });
      getWorkList({workType}).then((res : any)=>{
        state.stepList = res.data;
        if(!form.value.manageStepList||form.value.manageStepList==undefined||form.value.manageStepList.length==0){
          form.value.manageStepList = [];
          state.stepList.forEach((item:any)=>{
            form.value.manageStepList.push({"flowName":item.id});
          })
        }

      });
    }

    const initDialog = (type: string,row?: ProjectVO) => {
      useUser().getUserList({}).then((res: any) => {
        state.userList = res.data;
      });
      getProductlist({}).then((res:any)=>{
        state.productList = res.data;
      })
        if(type==="add"){
            state.dialog.title = "添加服务";
            nextTick(() => {
                reset();
            });
        }else{
            state.dialog.title = "修改【请填写功能名称】";
            nextTick(async () => {
                reset();
                const _id = row?.id as number;
                const res = await getProject(_id);
                Object.assign(form.value, res.data);
                handelProduct();
                if(form.value.startTime){
                  form.value.projectDate = [];
                  form.value.projectDate.push (form.value.startTime);
                  form.value.projectDate.push (form.value.endTime);
                }
                form.value. checkAdminIds = [];
                if(form.value.projectUserList){
                  form.value. checkAdminIds = [];
                  form.value.projectUserList.forEach((item)=>{
                    form.value. checkAdminIds.push(item.uid);
                  })
                }
              if(form.value.manageStepList){
                form.value.manageStepList.forEach((item)=>{
                  if(item.startTime){
                    item.projectDate = [];
                    item.projectDate.push (item.startTime);
                    item.projectDate.push (item.endTime);
                  }
                  if(item.flowIds){
                    item.checkAdminIds = [];
                    item.checkAdminIds = item.flowIds.split(",");
                  }
                })
              }
            });
        }
    };
    const openDialog = async (type: string, row: ProjectVO) => {
        initDialog(type, row);
        state.dialog.visible = true;
    };
    defineExpose({
      openDialog
    });

    const handelDell=(index)=>{
      form.value.manageStepList.splice(index,1);
    }

    const cancel = () => {
        state.dialog.visible = false;
        emit("refresh"); /* 刷新表格 */
    }
    /** 提交按钮 */
    const submitForm = () => {
        state.buttonLoading = true;
            projectFormRef.value.validate(async (valid: boolean) => {
              if(form.value.projectDate){
                form.value.startTime =form.value.projectDate[0];
                form.value.endTime =form.value.projectDate[1];
              }
              if(form.value.checkAdminIds){
                form.value. projectUserList = [];
                form.value.checkAdminIds.forEach((item)=>{
                  form.value. projectUserList.push({"uid":item});
                })
              }

              if(form.value.manageStepList){
                form.value.manageStepList.forEach((item)=>{
                  if(item.projectDate){
                    item.startTime =item.projectDate[0];
                    item.endTime =item.projectDate[1];
                  }
                  if(item.checkAdminIds){
                    item.flowIds= item.checkAdminIds.join(",");
                  }
                })
              }

            if (valid) {
                let res;
                let message;
                if (form.value.id) {
                    res = await updateProject(form.value)
                    message = "修改成功"
                } else {
                    res = await addProject(form.value)
                    message = "新增成功";
                }
                if (res.code === 200) {
                    ElMessage.success(message);
                    cancel();
                }else{
                    ElMessage.error(res.msg);
                }
            }
        });
        state.buttonLoading = false
    }
    const initFormData: ProjectForm = {
      id: undefined,
      name: undefined,
      productId: undefined,
      adminId: undefined,
      directorUid: undefined,
      startTime: undefined,
      endTime: undefined,
      status: "0",
      stepSort: undefined,
      content: undefined,
      mdContent: undefined,
      deleteTime: undefined,
      checkAdminIds:undefined,
      projectDate:undefined,
      projectUserList:undefined,
      manageStepList:undefined,
    }
</script>
